package com.lin.views;

import java.util.ArrayList;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;

public class MyFragmentAdapter extends FragmentPagerAdapter {
	private int length ;
	private ArrayList<Fragment> mFragments;//碎片数组
	private FragmentManager fm ;
	
	public MyFragmentAdapter(FragmentManager fm , ArrayList<Fragment> mFragments) {
		super(fm);
		this.fm = fm;
		this.length = mFragments.size();
		this.mFragments = mFragments;
		FragmentTransaction mTransaction = fm.beginTransaction();
	}

	@Override  
	public int getItemPosition(Object object) {  
		return POSITION_NONE; //这个是必须的  
	}  

	@Override
	public Fragment getItem(int position) {
		int size = mFragments.size();
		if(position >= size)
			return mFragments.get(size - 1);
		return mFragments.get(position);
	}

	@Override
	public int getCount() {
		return length;
	}

	public void setFragments(ArrayList<Fragment> fragments) {
		if(this.mFragments != null){
			FragmentTransaction ft = fm.beginTransaction();
			for(Fragment f:this.mFragments){
				ft.remove(f);
			}
			ft.commit();
			ft=null;
			fm.executePendingTransactions();
		}
		this.mFragments = fragments;
		notifyDataSetChanged();
	}
}
